<template>
  <template v-for="(item, index) in menuData" :key="index">
    <el-menu-item
      v-if="!Array.isArray(item.children)"
      v-show="hasPermission(item.index)"
      :key="index"
      :index="item.index"
    >
      <!-- <el-icon >
        <component v-if="item.icon" :is="item.icon || ''"/>
      </el-icon> -->
      <template #title>{{ item.title }}</template>
    </el-menu-item>
    <el-sub-menu v-show="getChildrenLength(item) > 0" :index="Math.floor(Math.random() * 1000000).toString()" v-else>
      <template #title>
        <el-icon>
          <component :is="item.icon || 'edit'" />
        </el-icon>
        <span>{{ item.title }}</span>
      </template>
      <MenuItem :menuData="item.children" />
    </el-sub-menu>
  </template>
</template>

<script setup>
import { computed } from 'vue'
import permissions from './../../config/permissions.js'
const props = defineProps({
  menuData: Array,
})

/* 
  @parmns path {String} 路由
  @params data {String} api
*/
const hasPermission = (path) => {
  if (path) {
    let permissionsAllData = []
    if (localStorage.getItem('permissions')) {
      permissionsAllData = JSON.parse(localStorage.getItem('permissions'))
    }
    let apis = permissions[path] 
    if (Array.isArray(apis)) {
      let flagData = apis.filter(item => permissionsAllData.includes(item))
      let flag = flagData.length
      if (!flag) {
        return false
      }
    }
  }
  return true
}

/*
* 判断是否有子集
* @params {Object} data 当前菜单数据
* */
const getChildrenLength = (data) => {
  let arr = []
  let children = data.children
  let permissionsAllData = []
  if (localStorage.getItem('permissions')) {
    permissionsAllData = JSON.parse(localStorage.getItem('permissions'))
  }
  if (Array.isArray(children) && children.length) {
    for(let i = 0; i < children.length; i++) {
      let path = children[i]['index']
      if(path) {
        let apis = permissions[path]
        if (Array.isArray(apis)) {
          let flagData = apis.filter(item => permissionsAllData.includes(item))
          arr = arr.concat(flagData)
        }
      }
    }
  }
  return arr.length
}
</script>

<style scoped>
.el-sub-menu .el-menu-item {
  margin-left: 15px;
}

</style>
